
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：交易提成                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-01-29 17:12:18                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： TradeCommissionService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BestTrader.Cms.Services
{
    public class TradeCommissionService : ITradeCommissionService
    {
        private readonly ITradeCommissionRepository _repository;
        private readonly IServiceChargeRepository _serviceChargeRepository;
        private readonly IManagerRepository _managerRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<TradeCommissionService> _logger;


        public TradeCommissionService(
            ITradeCommissionRepository repository
            , IServiceChargeRepository serviceChargeRepository
            , IManagerRepository managerRepository
            , IMapper mapper
            , ILogger<TradeCommissionService> logger)
        {
            _repository = repository;
            _managerRepository = managerRepository;
            _serviceChargeRepository = serviceChargeRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public TableDataModel LoadData(TradeCommissionRequestModel model, string UserId, string RoleId)
        {
            string conditions = "where IsDelete=0 ";//未删除的
            string Key = "";
            if (!model.Key.IsNullOrWhiteSpace())
            {
                //conditions += $"and (ProjectName like '%{model.Key}%' or ProjectCode like '%{model.Key}%')";
                conditions += $"and ProjectManagerId in(select Id from Manager where RealName like @Key or UserName like @Key) ";
                Key = model.Key.ToSqlLikeParam();

            }
            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc",new { Key=Key}).ToList();
            var viewList = new List<TradeCommissionListModel>();
            list.ForEach(x =>
            {
                var item = _mapper.Map<TradeCommissionListModel>(x);
                if (x.ProjectManagerId.HasValue)
                    item.ProjectManagerName = _managerRepository.GetUserNameAndRealNameById(x.ProjectManagerId.Value);
                item.ServiceChargePrice = _serviceChargeRepository.GetServiceChargePriceByCode(x.ProjectCode);
                viewList.Add(item);
            });
            return new TableDataModel
            {
                count = _repository.RecordCount(conditions, new { Key = Key }),
                data = viewList,
            };
        }

        public BaseResult AddOrModify(TradeCommissionAddOrModifyModel item, string UserId)
        {
            var result = new BaseResult();
            TradeCommission tradeCommission;
            var userId = UserId.ToInt32() ?? 0;
            var now = DateTime.Now;
            if (item.Id == 0)
            {
                var checkExist = _repository.GetList($"WHERE IsDelete=0 AND ProjectManagerId ={item.ProjectManagerId} AND ProjectCode= '{item.ProjectCode}'").FirstOrDefault();
                if (checkExist == null)
                {
                    //TODO ADD
                    tradeCommission = _mapper.Map<TradeCommission>(item);
                    tradeCommission.AddManagerId = userId;
                    tradeCommission.IsDefault = false;
                    tradeCommission.IsDelete = false;
                    tradeCommission.AddTime = now;
                    if (_repository.Insert(tradeCommission) > 0)
                    {
                        _logger.LogWarning($"管理员 UserId：{UserId} 添加了 代理ProjectManagerId：{tradeCommission.ProjectManagerId}的手续费,ProjectPrice->>{tradeCommission.ProjectPrice}<<-,ProjectCode->>{tradeCommission.ProjectCode}<<-");

                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExistPepeatDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExistPepeatDataMsg;

                }
            }
            else
            {
                //TODO Modify
                tradeCommission = _repository.Get(item.Id);
                if (tradeCommission != null)
                {

                    _mapper.Map(item, tradeCommission);
                    tradeCommission.ModifyManagerId = userId;
                    tradeCommission.ModifyTime = now;
                    if (_repository.Update(tradeCommission) > 0)
                    {
                        _logger.LogWarning($"管理员 UserId：{UserId} 修改了代理ProjectManagerId：{tradeCommission.ProjectManagerId}的手续费,ProjectPrice->>{tradeCommission.ProjectPrice}<<-,ProjectCode->{tradeCommission.ProjectCode},ProjectUnit->{tradeCommission.ProjectUnit}");
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                }
            }
            return result;
        }

        public BaseResult DeleteIds(int[] Ids)
        {
            var result = new BaseResult();
            if (Ids.Count() == 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonModelStateInvalidMsg;
            }
            else
            {
                var count = _repository.DeleteLogical(Ids);
                if (count > 0)
                {
                    //成功
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    //失败
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            return result;
        }

        public List<TradeCommissionListModel> LoadTradeCommissions(bool isDefault = false)
        {
            string conditions = "WHERE IsDelete=0 ";//未删除的
            if (isDefault)
            {
                conditions += "AND IsDefault=1 ";
            }
            var data = _repository.GetList(conditions);
            return _mapper.Map<List<TradeCommissionListModel>>(data);
        }
    }
}